package com.why.generate;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.DocxRenderData;
import com.deepoove.poi.data.MiniTableRenderData;
import com.deepoove.poi.data.RowRenderData;
import com.deepoove.poi.data.TextRenderData;
import com.why.dto.Api;
import org.apache.maven.plugin.MojoFailureException;

import java.io.File;
import java.io.FileOutputStream;
import java.util.*;
import java.util.stream.Collectors;

public class GenerateWordDoc {
    private static final RowRenderData header = new RowRenderData(Arrays.asList(new TextRenderData("FFFFFF", "序号"),
            new TextRenderData("FFFFFF", "参数项"),
            new TextRenderData("FFFFFF", "名称"),
            new TextRenderData("FFFFFF", "类型"),
            new TextRenderData("FFFFFF", "长度"),
            new TextRenderData("FFFFFF", "可空"),
            new TextRenderData("FFFFFF", "说明")),
            "87CEFF");

    public void generateWordDocByApis(List<Api> apiList, String templateFilePath, String outputFilePath) throws MojoFailureException {
        if (apiList == null || apiList.isEmpty()) {
            throw new MojoFailureException("初始化类加载器失败!");
        }

    }

    public void generateWordDocs(List<Api> apiList, String mainFilePath, String templateFilePath, String outputFilePath) throws Exception {
        Map<String, Object> mainData = new HashMap<>();
        List<Map<String, Object>> mainDataList = new ArrayList<>();
        for (Api api : apiList) {
            Map<String, Object> datas = assembleTemplateData(api);
            mainDataList.add(datas);
        }
        mainData.put("nested", new DocxRenderData(new File(templateFilePath), mainDataList));
        // 生成文件
        XWPFTemplate template = null;
        FileOutputStream out = null;
        try {
            template = XWPFTemplate.compile(mainFilePath).render(mainData);
            out = new FileOutputStream(outputFilePath);
            template.write(out);
            out.flush();
        } finally {
            out.close();
            template.close();
        }
    }

    /**
     * 根据Api对象生成Word文档
     * 使用说明查看官网http://deepoove.com/poi-tl/
     *
     * @param api
     */
    public void generateWordDoc(Api api, String templateFilePath, String outputFilePath) throws Exception {

        Map<String, Object> datas = assembleTemplateData(api);

        // 生成文件
        XWPFTemplate template = null;
        FileOutputStream out = null;
        try {
            template = XWPFTemplate.compile(templateFilePath).render(datas);
            out = new FileOutputStream(outputFilePath);
            template.write(out);
            out.flush();
        } finally {
            out.close();
            template.close();
        }
    }

    private Map<String, Object> assembleTemplateData(Api api) {
        // 表格的数据
        List<RowRenderData> tableDatas = api.getParams().parallelStream()
                .map(param -> RowRenderData.build(String.valueOf(param.getNo()), param.getName(),
                        param.getDescription(), param.getType(), param.getLength(),
                        param.getNullAble(), param.getRemark()))
                .collect(Collectors.toList());

        Map<List<RowRenderData>, String> requestTables = api.getRequestList().parallelStream()
                .collect(Collectors.toMap(request ->
                                request.getRequestParams().parallelStream().map(param ->
                                        RowRenderData.build(String.valueOf(param.getNo()), param.getName(),
                                                param.getDescription(), param.getType(), param.getLength(),
                                                param.getNullAble(), param.getRemark())).collect(Collectors.toList())
                        , Api.Request::getRequestClassName));
        // 表格的数据
        List<RowRenderData> responseData = api.getResponse().parallelStream()
                .map(param -> RowRenderData.build(String.valueOf(param.getNo()), param.getName(),
                        param.getDescription(), param.getType(), param.getLength(),
                        param.getNullAble(), param.getRemark()))
                .collect(Collectors.toList());
        return new HashMap<String, Object>() {
            {
                put("title", api.getTitle());
                put("url", api.getUrl());
                put("method", api.getMethod());
                put("explain", api.getExplain());
                if (!tableDatas.isEmpty()) {
                    put("params", new MiniTableRenderData(header, tableDatas, MiniTableRenderData.WIDTH_A4_FULL));
                }
                if (!requestTables.isEmpty()) {
                    List<Map<String, Object>> requestParamList = new ArrayList<>();
                    requestTables.forEach((key, value) -> {
                        Map<String, Object> requestParam = new HashMap<>();
                        requestParam.put("requestClassName", value);
                        requestParam.put("request", new MiniTableRenderData(header, key, MiniTableRenderData.WIDTH_A4_FULL));
                        requestParamList.add(requestParam);
                    });
                    put("request", new DocxRenderData(new File(api.getRequestTempleFilePath()), requestParamList));
                }

                if (!responseData.isEmpty()) {
                    put("response", new MiniTableRenderData(header, responseData, MiniTableRenderData.WIDTH_A4_FULL));
                }
            }
        };
    }

}
